package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.ReadingTypeDAO;
import ee.maoinvest.backend.model.data.ReadingType;

public class ReadingTypeDAOPostgresqlImpl implements ReadingTypeDAO
{
	
	Logger logger = Logger.getLogger(ReadingTypeDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	
	public ReadingTypeDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}

	@Override
	public ReadingType getReadingTypeByID(int readingTypeID) 
	{
		resultSet = null;
		ReadingType readingTypeRetrieved = null;
		sql = "SELECT * FROM Reading_types WHERE readingTypeID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, readingTypeID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				readingTypeRetrieved = new ReadingType();
				readingTypeRetrieved.setReadingTypeID(resultSet.getInt("readingTypeID"));
				readingTypeRetrieved.setTypeName(resultSet.getString("typeName"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return readingTypeRetrieved;
	}
}
